<?php

	class PHPExcelExport{

		private static $objPHPExcel = null;
		private static $objPhpSheet = null;

		function __construct(){
			date_default_timezone_set('Asia/Shanghai');
			if (PHP_SAPI == 'cli') die('请使用浏览器进行操作！');
			//self::getInstance();
		}

		public  static function getExportPage($filePath,$sheetIndex=0,$sheetTitle,$index=1,$field,$dataIndex=2,$dataList){
			PHPExcelExport::createSheet($filePath,$sheetIndex,$sheetTitle);
			PHPExcelExport::setFirstRow($filePath,$index,$field);
			PHPExcelExport::setDataRow($filePath,$dataIndex,$dataList);
			PHPExcelExport::saveExport($sheetTitle);
		}

		public static function getInstance($filePath){
			//include_once ('D:/prog_tools/wamp/www/elective_system/application/library/PHPExcel.php');
			include_once($filePath);
			if (self::$objPHPExcel==null) {
				self::$objPHPExcel = new PHPExcel();
			}
			return self::$objPHPExcel;
		}

		public static function createSheet($filePath,$sheetindex=0,$sheetTitle){
	        self::getInstance($filePath);
	        self::$objPHPExcel->createSheet();
			self::$objPHPExcel->setActiveSheetIndex($sheetindex);
			self::$objPhpSheet = self::$objPHPExcel->getActiveSheet();
			self::$objPhpSheet->setTitle($sheetTitle);
	    }

		public static function setFirstRow($filePath,$k=1,$field){
			self::getInstance($filePath);
	        foreach($field as $key=> $val){
	            self::$objPhpSheet->setCellValue($key.$k, $val);
	        }
	    }

	    public static function setDataRow($filePath,$index=2,$dataList){
	    	self::getInstance($filePath);
	    	foreach ($dataList as $data) {
	    		foreach ($data as $k => $v) {
	    			self::$objPhpSheet->setCellValue($k . $index, $v);
	    		}
	    		$index++;
	    	}
	    }

	    public static function saveExport($sheetTitle){

	    	/*self::$objPHPExcel->getActiveSheet()->setTitle($sheetTitle);  

			//设置打开文件时显示的sheet
			self::$objPHPExcel->setActiveSheetIndex(0);*/  

			//设置文件类型
			header('Content-Type: application/vnd.ms-excel;');
			//设置默认的文件名 
			header('Content-Disposition: attachment;filename="'.$sheetTitle.'.xls"'); 
			header('Cache-Control: max-age=0');
			// 针对 IE 9
			header('Cache-Control: max-age=1');
			header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
			header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
			header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
			header ('Pragma: public'); // HTTP/1.0

			$objWriter = PHPExcel_IOFactory::createWriter(self::$objPHPExcel, 'Excel5');
			$objWriter->save("php://output");
			exit();
	    }
	}

?>